# -*- coding: utf-8 -*-
"""
Created on Wed Feb 11 19:16:16 2015

@author: aaron
"""

import pymongo

class dbopt():
    def __init__(self):
        con = pymongo.Connection('localhost',27017)
        self.webchat = con.webchat
        self.chat = self.webchat.chat
        self.room = self.webchat.room
    def get_online(self):
        rescu = self.room.find({},{'users_in': 1 })
        result = []
        if not rescu[0].has_key('users_in'):
            return result
        for x in rescu:
            result=result+x['users_in']
        return result
    def add_online(self,user,room_id):
        self.room.update({'room_id':room_id},{'$push':{'users_in':user}})
        print user+"is online in "+room_id
    def add_room(self,room_id,create):
        self.room.insert({'room_id':room_id,'users_in':create})
        print create+"create "+room_id
    def change_room(self,old_room_id,new_room_id,user):
        cu = self.room.find({'room_id':new_room_id})
        if len(cu)==0:
            self.add_room(new_room_id,user)
        else:
            self.room.update({'room_id':old_room_id},{'$pull':{'users_in':user}})
            self.add_online(user,new_room_id)
    def set_outline(self,user):
        self.room.update({'users_in':user},{'$pull':{'users_in':user}})
        print user+' outline'
    def user_in_room(self,room_id):
        print room_id
        cucu = self.room.find({'room_id':room_id})
        result = []
        print cucu.count()
        result = cucu[0]['users_in']
        print result
        return result
    def chat(self,user,room_id,info,time):
        self.chat.insert({'user':user,'room_id':room_id,'info':info,'time':time})
        print user+" : "+info
    def get_chat(self,room_id):
        cu = self.chat.find({'room_id':room_id})
        result = []
        if cu.count() == 0:
            return result
        for x in cu:
            result.append(x)
        return result
        
    
        
        
        